package com.sj.uabrowser.web;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.just.agentweb.AgentWeb;
import com.sj.uabrowser.app.Constant;
import com.sj.uabrowser.app.SPUtil;
import com.sj.uabrowser.app.Util;
import com.sj.uabrowser.mvp.main.view.act.SearchAct;

/**
 * Created by Xijun.Wang on 2018/1/25.
 */

public class BrowserWebViewFactory implements WebViewFactory {
    private final Context mContext;
    private AgentWeb mAgentWeb;
    public BrowserWebViewFactory(Context context) {
        mContext = context;
    }
    private WebView instantiateWebView(AttributeSet attrs, int defStyle) {
        FrameLayout frameLayout = new FrameLayout(mContext);
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        frameLayout.setLayoutParams(lp);
        return loadSearchPage(frameLayout,null);
//        return null;
//                new WebView(mContext, attrs, defStyle);
    }
    @Override
    public WebView createWebView() {
        WebView w = instantiateWebView(null, android.R.attr.webViewStyle);
        initWebViewSettings(w);
        return w;
    }

    protected void initWebViewSettings(WebView w) {
        w.setScrollbarFadingEnabled(true);
        w.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        // Enable the built-in zoom
        WebSettings settings = w.getSettings();
        settings.setBuiltInZoomControls(true);
        settings.setDomStorageEnabled(true);
        settings.setJavaScriptEnabled(true);
        /// M: Add to disable overscroll mode
        w.setOverScrollMode(View.OVER_SCROLL_NEVER);
        final PackageManager pm = mContext.getPackageManager();
        boolean supportsMultiTouch =
                pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH)
                        || pm.hasSystemFeature(PackageManager.FEATURE_FAKETOUCH_MULTITOUCH_DISTINCT);
        w.getSettings().setDisplayZoomControls(!supportsMultiTouch);
        CookieManager cookieManager = CookieManager.getInstance();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.setAcceptThirdPartyCookies(w, cookieManager.acceptCookie());
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // Remote Web Debugging is always enabled, where available.
            WebView.setWebContentsDebuggingEnabled(true);
        }
    }

    private WebView loadSearchPage(FrameLayout mViewParent,String url) {
        mAgentWeb = AgentWeb.with((Activity) mContext)
                .setAgentWebParent(mViewParent, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebViewClient(webViewClient)
                .createAgentWeb()
                .ready()
                .go(url);
        WebView webView = mAgentWeb.getWebCreator().getWebView();
//        WebView初始化之后需要添加如下代码开启Cookie：
        if (android.os.Build.VERSION.SDK_INT >= 21) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
        } else {
            CookieManager.getInstance().setAcceptCookie(true);
        }
        WebSettings webSettings = webView.getSettings();
        int fontSize = SPUtil.get(mContext,SPUtil.KEY_FONTSIZE, Constant.FONTSIZE_NORMAL);
        webSettings.setDefaultFontSize(fontSize);
        webSettings.setSupportZoom(true);
        //支持javascript
        webSettings.setJavaScriptEnabled(true);
// 设置可以支持缩放
        webSettings.setSupportZoom(true);
// 设置出现缩放工具
        webSettings.setBuiltInZoomControls(true);
//扩大比例的缩放
        webSettings.setUseWideViewPort(true);
//自适应屏幕
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//        webSettings.setLoadWithOverviewMode(true);
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Intent intentUrl = new Intent(mContext, SearchAct.class);
                intentUrl.putExtra("httpurl", url);
                mContext.startActivity(intentUrl);
            }
        });
        return webView;
    }

    private WebViewClient webViewClient = new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            Uri uri = request.getUrl();
            String uriOverride = uri.toString();
            Log.e("uriOverride:", uriOverride);
            if (uriOverride.startsWith("baiduboxlite://")
                    || uriOverride.startsWith("baiduboxapp://")
                    || uriOverride.startsWith("iqiyi://")
                    || uriOverride.startsWith("https://mo.baidu.com/boxandroid")
                    || uriOverride.startsWith("tbopen://")
                    ||uriOverride.startsWith("suning://")

            ) {
                return true;
            }
            return false;
        }


        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            Uri uri = request.getUrl();
            return super.shouldInterceptRequest(view, request);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (mAgentWeb != null) {
                mAgentWeb.getIndicatorController().setProgress(100);
            }
//            if(type == TYPE_SEARCH&&!noTrace){
//                bean.setTitle(view.getTitle());
//                daoSession.update(bean);
//            }
        }
    };
}
